<template>
    <div class="drawMapDiv">
        <div class="drawMap" id="drawMap">

        </div>
		<div id="toolbars">
		    <el-button size="mini" type="primary" icon="" @click.stop="DrawPolygon">绘制多边形</el-button>
		    <el-button size="mini" type="success" @click.stop="save">保存</el-button>
		</div>
    </div>

</template>
<script>
    import mapConfig from "../../../assets/json/mapConfig.json";

    export default {
        data(){
            return{
                map:null,
                layer:null,
                formData:{
                    id:"",
                    surfacesPosition:""
                }
            }
        },
        methods:{
            initMap(){
                var self = this;
                let map = L.map("drawMap", {
                    minZoom: 3,
                    maxZoom: 18,
                    center: mapConfig.center,
                    zoom: mapConfig.zoom,
                    zoomControl: false,
                    attributionControl: false,
                    crs: L.CRS.EPSG3857
                });

                //控制地图底图
                var baseLayers = {
                    "高德地图": L.tileLayer('http://webrd0{s}.is.autonavi.com/appmaptile?lang=zh_cn&size=1&scale=1&style=8&x={x}&y={y}&z={z}', { subdomains: "1234" }),
                    "高德影像": L.layerGroup(
                        [
                            L.tileLayer('http://webst0{s}.is.autonavi.com/appmaptile?style=6&x={x}&y={y}&z={z}', { subdomains: "1234" }),
                            L.tileLayer('http://webst0{s}.is.autonavi.com/appmaptile?x={x}&y={y}&z={z}&lang=zh_cn&size=1&scale=1&style=8', { subdomains: "1234" })
                        ]
                    ),
                    //天地图tk可以换成自己申请的key
                    "天地图": L.layerGroup([
                        L.tileLayer('http://t{s}.tianditu.gov.cn/vec_w/wmts?SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=vec&STYLE=default&TILEMATRIXSET=w&FORMAT=tiles&TILECOL={x}&TILEROW={y}&TILEMATRIX={z}&tk=56b81006f361f6406d0e940d2f89a39c', { subdomains: ['0', '1', '2', '3', '4', '5', '6', '7'] }),
                        L.tileLayer('http://t{s}.tianditu.gov.cn/cva_w/wmts?SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=cva&STYLE=default&TILEMATRIXSET=w&FORMAT=tiles&TILECOL={x}&TILEROW={y}&TILEMATRIX={z}&tk=56b81006f361f6406d0e940d2f89a39c', { subdomains: ['0', '1', '2', '3', '4', '5', '6', '7'] })
                    ]),
                    "天地图影像": L.layerGroup([
                        L.tileLayer('http://t{s}.tianditu.gov.cn/img_w/wmts?SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=img&STYLE=default&TILEMATRIXSET=w&FORMAT=tiles&TILECOL={x}&TILEROW={y}&TILEMATRIX={z}&tk=56b81006f361f6406d0e940d2f89a39c', { subdomains: ['0', '1', '2', '3', '4', '5', '6', '7'] }),
                        L.tileLayer('http://t{s}.tianditu.gov.cn/cia_w/wmts?SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=cia&STYLE=default&TILEMATRIXSET=w&FORMAT=tiles&TILECOL={x}&TILEROW={y}&TILEMATRIX={z}&tk=56b81006f361f6406d0e940d2f89a39c', { subdomains: ['0', '1', '2', '3', '4', '5', '6', '7'] })
                    ]).addTo(map),
                    "天地图地形": L.layerGroup([
                        L.tileLayer('http://t{s}.tianditu.gov.cn/ter_w/wmts?SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=ter&STYLE=default&TILEMATRIXSET=w&FORMAT=tiles&TILECOL={x}&TILEROW={y}&TILEMATRIX={z}&tk=56b81006f361f6406d0e940d2f89a39c', { subdomains: ['0', '1', '2', '3', '4', '5', '6', '7'] }),
                        L.tileLayer('http://t{s}.tianditu.gov.cn/cta_w/wmts?SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=cta&STYLE=default&TILEMATRIXSET=w&FORMAT=tiles&TILECOL={x}&TILEROW={y}&TILEMATRIX={z}&tk=56b81006f361f6406d0e940d2f89a39c', { subdomains: ['0', '1', '2', '3', '4', '5', '6', '7'] })
                    ]),

                    "Google地图": L.tileLayer('http://mt1.google.cn/vt/lyrs=m@207000000&hl=zh-CN&gl=CN&src=app&x={x}&y={y}&z={z}&s=Galile'),
                    "Google影像": L.layerGroup([
                        L.tileLayer('http://mt1.google.cn/vt/lyrs=s&hl=zh-CN&gl=CN&x={x}&y={y}&z={z}&s=Gali'),
                        L.tileLayer('http://mt1.google.cn/vt/imgtp=png32&lyrs=h@207000000&hl=zh-CN&gl=cn&x={x}&y={y}&z={z}&s=Galil')
                    ]),

                    "GeoQ ": L.tileLayer('http://map.geoq.cn/ArcGIS/rest/services/ChinaOnlineCommunity/MapServer/tile/{z}/{y}/{x}'),
                    "GeoQ 藏蓝": L.tileLayer('http://map.geoq.cn/ArcGIS/rest/services/ChinaOnlineStreetPurplishBlue/MapServer/tile/{z}/{y}/{x}'),
                    "GeoQ 灰": L.tileLayer('http://map.geoq.cn/ArcGIS/rest/services/ChinaOnlineStreetGray/MapServer/tile/{z}/{y}/{x}')
                };
                //topright
                L.control.layers(baseLayers, {}, { position: "topright" }).addTo(map);

                L.control.zoom({
                    position: 'bottomright'
                }).addTo(map);
                this.map = map; //data上需要挂载
                this.layer = L.layerGroup().addTo(map);
                this.getGpsElectronicFence();
            },
            //多边形绘画
            DrawPolygon() {
                var self = this;
                var points = []
                var lines = new L.polyline([])
                var tempLines = new L.polygon([])
                self.map.on('click', onClick);    //点击地图
                self.map.on('dblclick', onDoubleClick);//双击完成
                self.map.on('mousemove', onMove)
                function onClick(e) {
                    points.push([e.latlng.lat, e.latlng.lng])
                    lines.addLatLng(e.latlng)
                    self.layer.addLayer(lines)
                    self.layer.addLayer(L.circle(e.latlng, { color: '#ff0000', fillColor: 'ff0000', fillOpacity: 1 }))

                }
                function onMove(e) {
                    if (points.length > 0) {
                        var ls = [points[points.length - 1], [e.latlng.lat, e.latlng.lng]]
                        tempLines.setLatLngs(ls)
                        self.layer.addLayer(tempLines)
                    }
                }

                function onDoubleClick(e) {
                    if(self.layer){
                        self.layer.clearLayers();
                    }
                    L.polygon([points]).addTo(self.layer);
                    points = []
                    lines = new L.polyline([])
                }
         },
            addToMap(){
                var startIndex = this.formData.surfacesPosition.lastIndexOf("(")+1;
                var endIndex = this.formData.surfacesPosition.indexOf(")");
                var points = [],strPoints = this.formData.surfacesPosition.substring(startIndex,endIndex);
                var p = strPoints.split(",");
                for(var i = 0;i < p.length;i++){
                    var po = p[i].split(" ");
                    points.push([po[0],po[1]]);
                }
               var polygon = L.polygon([points]).addTo(this.layer);
                this.map.fitBounds(polygon.getBounds());
            },
            save(){
                var geoJson = this.layer.toGeoJSON()
                if(geoJson.features.length == 0){
                    this.$message.warning("请绘制一个范围！！！")
                    return;
                }
                var feature = geoJson.features[0];
                var points = feature.geometry.coordinates[0];
                 var wkt = "POLYGON((" ;
                 for(var i = 0;i < points.length;i++){
                  if(i == points.length-1){
                      wkt+=points[i][1]+" "+points[i][0]
                  }else {
                      wkt+=points[i][1]+" "+points[i][0]+","
                  }
                 }
                wkt += "))"
                this.formData.surfacesPosition = wkt;
              this.$http.gpsElectronicFenceAdd( this.formData).then(res => {
                if(res.data.code == 200){
                    this.$message.success("保存成功！！");
                    this.formData.id = res.data.data.id;
                    this.formData.surfacesPosition = res.data.data.surfacesPosition;
                }else{
                    this.$message.error(res.data.message)
                }
              }).catch(err => {
                  throw ( err );
              });
            },
            getGpsElectronicFence(){
                this.$http.getGpsElectronicFence().then(res=>{
                   if(res.data.data && res.data.data.length > 0){
                       var feature = res.data.data[0];
                       this.formData.id = feature.id;
                       this.formData.surfacesPosition = feature.surfacesPosition;
                       this.addToMap();
                   }
                }).catch(err=>{
                    throw (err);
                })
            }
        },
        mounted(){
           this.initMap();
          // this.getGpsElectronicFence();
        }
    }
</script>
<style scoped lang="scss">
    .drawMapDiv{
        width: 100%;
        height: 100%;
		position: relative;
        .drawMap{
            width: 100%;
            height: 100%;
        }
        #toolbars{
            position: absolute;
            top: 10px;
			left:10px;
            z-index: 123334;
        }
    }
</style>
